package com.borqs.samples;

import java.io.PrintWriter;
import java.io.StringWriter;
import android.util.*;
import android.os.*;
import android.content.*;
import com.android.internal.os.ProcessStats;

public class ProcessSampler extends ASampler{
    private final static String TAG = "ProcessSampler";
    private ProcessStats mStat;
    public ProcessSampler(DBHelper helper){
        super(helper);
        mStat = new ProcessStats(false);
        mStat.init();
    }
    @Override public void sample(long sample_id){
        mStat.update();//sample
        Log.d(TAG,"<<<process sample>>> @sample_id="+sample_id);
        for(int j = 0;j< mStat.countStats();j++){
            ProcessStats.Stats st = mStat.getStats(j);
            if(st.rel_uptime!=0){
                int totalTime = (int)(st.rel_uptime+5)/10;//note about this
                int user = st.rel_utime;
                int system = st.rel_stime;
                int mysum = user+system;
                if((st.rel_utime&st.rel_stime) != 0){
                    String ratio_s = getRatio(mysum,totalTime);
                    double ratio_d = Double.parseDouble(ratio_s);
                    if(ratio_d > 0)
                        Log.d(TAG,st.pid+"/"+st.name+"==>"
                            +" rel_uptime="+totalTime
                            +",rel_utime="+user
                            +",rel_stime="+system
                            +",ratio="+getRatio(mysum,totalTime)+"%");
                        dbSave(sample_id,st.pid,st.name,st.rel_utime,st.rel_stime,st.rel_uptime);
                }
            }
        }
    }
    private void dbSave(long sample_id,int pid,String name,long rel_utime,long rel_stime,long rel_uptime){
        ContentValues cv = new ContentValues();
        cv.put("pid",pid);
        cv.put("name",name);
        cv.put("rel_utime",rel_utime);
        cv.put("rel_stime",rel_stime);
        cv.put("rel_uptime",rel_uptime);
        cv.put("sample_id",sample_id);
        helper.getWritableDatabase().insert("process_samples",null,cv);
    }
    /**
    * @param denominator this is total
    */
    private String getRatio(long numerator, long denominator) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        long thousands = (numerator*1000)/denominator;
        long hundreds = thousands/10;
        pw.print(hundreds);
        if (hundreds < 10) {
            long remainder = thousands - (hundreds*10);
            if (remainder != 0) {
                pw.print('.');
                pw.print(remainder);
            }
        }
        return sw.toString();
    }
}
